package com.enation.app.javashop.seller.api.shop;


import com.enation.app.javashop.core.base.context.Region;
import com.enation.app.javashop.core.base.context.RegionFormat;
import com.enation.app.javashop.core.goods.model.dos.CategoryDO;
import com.enation.app.javashop.core.goods.service.CategoryManager;
import com.enation.app.javashop.core.shop.model.dos.Clerk;
import com.enation.app.javashop.core.shop.model.dto.*;
import com.enation.app.javashop.core.shop.model.enums.ShopStatusEnum;
import com.enation.app.javashop.core.shop.model.vo.ShopInfoVO;
import com.enation.app.javashop.core.shop.model.vo.ShopSettingVO;
import com.enation.app.javashop.core.shop.model.vo.ShopVO;
import com.enation.app.javashop.core.shop.model.vo.SubmitFinanceInfoVO;
import com.enation.app.javashop.core.shop.model.vo.operator.SellerEditShop;
import com.enation.app.javashop.core.shop.service.ClerkManager;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Buyer;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DictUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 店铺相关API
 *
 * @author zhangjiping
 * @version v7.0.0
 * @since v7.0.0
 * 2018年3月30日 上午10:54:57
 */
@Api(description = "店铺相关API")
@RestController
@RequestMapping("/seller/shops")
@Validated
public class ShopSellerController {
    @Autowired
    private ShopManager shopManager;

    @Autowired
    private ClerkManager clerkManager;

    @Autowired
    private CategoryManager categoryManager;

    public static String noShop = "NO_SHOP";

    @ApiOperation(value = "修改店铺设置", response = ShopSettingVO.class)
    @ApiImplicitParam(name = "shop_name", value = "店铺名称", required = true, dataType = "String", paramType = "query")
    @PutMapping()
    public ShopSettingVO edit(@Valid ShopSettingDTO shopSetting, @RegionFormat @RequestParam("shop_region") Region shopRegion, String shopName) {
        //修改店铺信息
        ShopVO shopVO = this.shopManager.getShop(UserContext.getSeller().getSellerId());
        shopVO.setShopName(shopName);
        shopVO.setShopLat(shopSetting.getShopLat());
        shopVO.setShopLng(shopSetting.getShopLng());
        this.shopManager.editShopInfo(shopVO);
        //修改店铺详细信息
        shopSetting.setShopProvince(shopRegion.getProvince());
        shopSetting.setShopCity(shopRegion.getCity());
        shopSetting.setShopCounty(shopRegion.getCounty());
        shopSetting.setShopTown(shopRegion.getTown());
        shopSetting.setShopProvinceId(shopRegion.getProvinceId());
        shopSetting.setShopCityId(shopRegion.getCityId());
        shopSetting.setShopCountyId(shopRegion.getCountyId());
        shopSetting.setShopTownId(shopRegion.getTownId());

        if (shopSetting.getOpenTimeType() == 1) {
            shopSetting.setOpenTime("[{\"start_time\":\"00:00\",\"end_time\":\"24:00\"}]");
        }
        this.shopManager.editShopSetting(shopSetting);
        ShopSettingVO shopSettingVO = new ShopSettingVO();
        BeanUtils.copyProperties(shopSetting, shopSettingVO);
        shopSettingVO.setShopName(shopName.trim());
        return shopSettingVO;
    }


    @ApiOperation(value = "修改店铺Logo", response = SellerEditShop.class)
    @PutMapping(value = "/logos")
    @ApiImplicitParam(name = "logo", value = "图片路径", required = true, dataType = "String", paramType = "query")
    public SellerEditShop editShopLogo(@ApiIgnore @NotEmpty(message = "店铺logo必填") String logo) {
        SellerEditShop sellerEdit = new SellerEditShop();
        Seller seller = UserContext.getSeller();
        sellerEdit.setSellerId(seller.getSellerId());
        sellerEdit.setOperator("修改店铺logo");
        shopManager.editShopOnekey("shop_logo", logo);
        return sellerEdit;
    }


    @ApiOperation(value = "修改货品预警数设置", response = SellerEditShop.class)
    @PutMapping(value = "/warning-counts")
    @ApiImplicitParam(name = "warning_count", value = "预警货品数", required = true, dataType = "String", paramType = "query")
    public SellerEditShop editWarningCount(@ApiIgnore @NotNull(message = "预警货品数必填") String warningCount) {
        SellerEditShop sellerEdit = new SellerEditShop();
        Seller seller = UserContext.getSeller();
        sellerEdit.setSellerId(seller.getUid());
        sellerEdit.setOperator("修改货品预警数");
        this.shopManager.editShopOnekey("goods_warning_count", warningCount);
        return sellerEdit;
    }

    @ApiOperation(value = "获取店铺信息", response = ShopVO.class)
    @GetMapping
    public ShopInfoVO get() {
        Seller seller = UserContext.getSeller();
        ShopVO shop =null;
        if(seller==null){
            // 店铺审核不通过，使用买家身份获取店铺信息
            Buyer buyer = UserContext.getBuyer();
            shop = shopManager.getShopByMemberId(buyer.getUid());
        }else{
             // 店铺审核成功查询店铺信息
             shop = shopManager.getShop(seller.getSellerId());
        }
        String categorys = shop.getGoodsManagementCategory();
        String categoryNames="";
        if(!StringUtils.isEmpty(categorys)){
            String[] categoryIds = categorys.split(",");
            for (String categoryId : categoryIds) {
                CategoryDO categoryDO = this.categoryManager.getModel(Integer.valueOf(categoryId));
                if(categoryDO!=null){
                    categoryNames=categoryNames+" "+categoryDO.getName();
                }
            }
        }
        shop.setCategoryNames(categoryNames);
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        BeanUtil.copyProperties(shop,shopInfoVO);
        return shopInfoVO;
    }

    @ApiOperation(value = "获取店铺状态")
    @GetMapping(value = "/status")
    public String getShopStatus() {
        Buyer buyer = UserContext.getBuyer();
        if(buyer == null){
            return "OPEN";
        }
        Clerk clerk = clerkManager.getClerkByMemberId(buyer.getUid());
        if (clerk != null && clerk.getUserState().equals(0)) {
            ShopVO shopVO = shopManager.getShop(clerk.getShopId());
            return shopVO.getShopDisable();
        }
        return noShop;
    }

    @ApiOperation(value = "APP获取店铺状态")
    @GetMapping(value = "/statusInfo")
    public Map getShopStatusInfo() {
        String shopStatus = ShopStatusEnum.UN_APPLY.value();
        String statusReason = "";
        ShopVO shopVO = shopManager.getShopByMemberId(UserContext.getBuyer().getUid());
        if(shopVO==null){
            Clerk clerk = clerkManager.getClerkByMemberId(UserContext.getBuyer().getUid());
            if (clerk != null && clerk.getUserState().equals(0)) {
                shopVO = shopManager.getShop(clerk.getShopId());
            }
        }
        if(shopVO!=null){
            shopStatus = shopVO.getShopDisable();
        }
        Map<String, String> shopStatusInfo = Maps.newHashMap();
        shopStatusInfo.put("shop_staus", shopStatus);
        if (shopStatus != ShopStatusEnum.OPEN.value()) {
            if (shopStatus.equals(ShopStatusEnum.REFUSED.name())) {
                statusReason = "店铺申请信息不完整，请按要求填写!";
            }
            if (shopStatus.equals(ShopStatusEnum.CLOSED.name())) {
                statusReason = "店铺不满足运营资质，被关闭!";
            }
            shopStatusInfo.put("status_reason", statusReason);
        }
        return shopStatusInfo;
    }

    @ApiOperation(value = "获取店铺配送支持类型")
    @GetMapping(value = "/shipType")
    public String getShipType() {
        Seller seller = UserContext.getSeller();
        ShopVO shopVO = shopManager.getShop(seller.getSellerId());
        return shopVO.getShipType();
    }

    @ApiOperation(value = "商家发票设置")
    @PutMapping(value = "/receipt")
    public void receiptSetting(@Valid ShopReceiptDTO shopReceiptDTO) {

        this.shopManager.receiptSetting(shopReceiptDTO);
    }

    @ApiOperation(value = "提交财务信息")
    @PutMapping("/submit-finance-info")
    public boolean submitFinanceInfo(@Valid SubmitFinanceInfoVO submitFinanceInfoVO,
                                     @RegionFormat @RequestParam("bank_region") Region bankRegion) {
        submitFinanceInfoVO.setBankProvince(bankRegion.getProvince());
        submitFinanceInfoVO.setBankCity(bankRegion.getCity());
        submitFinanceInfoVO.setBankCounty(bankRegion.getCounty());
        submitFinanceInfoVO.setBankTown(bankRegion.getTown());
        submitFinanceInfoVO.setBankProvinceId(bankRegion.getProvinceId());
        submitFinanceInfoVO.setBankCityId(bankRegion.getCityId());
        submitFinanceInfoVO.setBankCountyId(bankRegion.getCountyId());
        submitFinanceInfoVO.setBankTownId(bankRegion.getTownId());
        return shopManager.submitFinanceInfo(submitFinanceInfoVO);
    }

    @ApiOperation(value = "綁定银行卡信息", response = ShopVO.class)
    @PostMapping("/bindBankCard")
    public boolean bindBankCard(@RequestBody ShopBankCardDTO bankCardInfo) {
        Seller seller = UserContext.getSeller();
        bankCardInfo.setShopId(seller.getSellerId());
        shopManager.updateBankCard(bankCardInfo);
        return true;
    }


    @ApiOperation(value = "提交建议反馈")
    @PostMapping(value = "/feedBack")
    public void feedBack(@Valid @RequestBody SellerFeedBackDTO feedBackDTO) {
        // TODO
        System.out.println(feedBackDTO);
    }

    /**
     * APP 修改店铺信息
     * @param appEditShopDTO
     */
    @ApiOperation(value = "APP端修改店铺信息")
    @PostMapping(value = "/editShop")
    public void appEditShop(@RequestBody AppEditShopDTO appEditShopDTO ) {
        ShopVO shopVO = this.shopManager.getShop(UserContext.getSeller().getSellerId());
        if(StringUtils.isNotEmpty(appEditShopDTO.getLegalImg())){
            shopVO.setLegalImg(appEditShopDTO.getLegalImg());
        }
        if(StringUtils.isNotEmpty(appEditShopDTO.getLinkName())){
            shopVO.setLinkName(appEditShopDTO.getLinkName());
        }
        if(StringUtils.isNotEmpty(appEditShopDTO.getLinkPhone())){
            shopVO.setLinkPhone(appEditShopDTO.getLinkPhone());
        }
        if(StringUtils.isNotEmpty(appEditShopDTO.getShopDesc())){
            shopVO.setShopDesc(appEditShopDTO.getShopDesc());
        }
        if(StringUtils.isNotEmpty(appEditShopDTO.getShopLogo())){
            shopVO.setShopLogo(appEditShopDTO.getShopLogo());
        }
        if(StringUtils.isNotEmpty(appEditShopDTO.getShopDesc())){
            shopVO.setShopName(appEditShopDTO.getShopName());
        }
        if (appEditShopDTO.getBusinessStatus() != null) {
            shopVO.setBusinessStatus(appEditShopDTO.getBusinessStatus());
        }
        if (appEditShopDTO.getOpenTimeType() != null) {
            shopVO.setOpenTimeType(appEditShopDTO.getOpenTimeType());
        }
        if (StringUtils.isNotEmpty(appEditShopDTO.getOpenTime())) {
            shopVO.setOpenTime(appEditShopDTO.getOpenTime());
        }
        this.shopManager.editShopInfo(shopVO);
    }


    @ApiOperation(value = "是否社区团购店铺")
    @GetMapping(value = "/isShetuanShop")
    public Boolean isShetuan() {
        Seller seller = UserContext.getSeller();
        if(seller==null){
         throw new ServiceException("10000","请先登录店铺账号");
        }
        Integer sellerId = seller.getSellerId();
        String dictValue = DictUtils.getDictValue("", "SHETUAN_SELLER", "SHETUAN_SELLER");
        return StringUtils.isNotEmpty(dictValue) && dictValue.contains(sellerId+"");
    }
}
